package com.yangxk.kadmin.web.module.sample.service.impl;

import com.yangxk.kadmin.common.base.AbstractService;
import com.yangxk.kadmin.common.support.generator.IdGenerator;
import com.yangxk.kadmin.common.exception.BizException;
import com.yangxk.kadmin.common.exception.ParamException;
import com.yangxk.kadmin.web.common.enumeration.ResponseCode;
import com.yangxk.kadmin.web.module.sample.form.BookEditForm;
import com.yangxk.kadmin.web.module.sample.form.BookQueryForm;
import com.yangxk.kadmin.web.module.sample.mapper.BookMapper;
import com.yangxk.kadmin.web.module.sample.po.Book;
import com.yangxk.kadmin.web.module.sample.service.BookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yangxk.kadmin.common.support.BeanValidator;
import org.springframework.transaction.annotation.Transactional;
import com.yangxk.kadmin.web.common.datascope.DataScope;
import com.yangxk.kadmin.web.module.sample.vo.BookVo;

import java.util.List;

@Service
public class BookServiceImpl extends AbstractService<Book, Long> implements BookService {

    @Autowired
    private BookMapper bookMapper;


    @Override
    @DataScope
    public PageInfo<BookVo> queryByPage(BookQueryForm bookQueryForm) {

        PageHelper.startPage(bookQueryForm.getPageNum(), bookQueryForm.getPageSize());

        List<BookVo> bookList = bookMapper.selectList(bookQueryForm);

        return new PageInfo<>(bookList);
    }

    @Transactional
    @Override
    public long addBook(BookEditForm form) {
        BeanValidator.check(form);
        Book book = new Book();
        BeanUtils.copyProperties(form, book);

        book.setId(IdGenerator.getId());
        // TODO 设置创建 更新时间
        bookMapper.insertSelective(book);

        return book.getId();
    }

    @Override
    @Transactional
    public long updateBook(BookEditForm updateForm) {
        BeanValidator.check(updateForm);

        if (updateForm.getId() == null)
            throw new ParamException("id不能为空");

        Book book = bookMapper.selectByPrimaryKey(updateForm.getId());
        if (book == null)
            throw new BizException(ResponseCode.UPDATE_CHECK_NULL);

        Book update = new Book();
        BeanUtils.copyProperties(updateForm, update);
        // TODO 设置更新时间

        bookMapper.updateByPrimaryKeySelective(update);
        return book.getId();
    }

    @Override
    @Transactional
    public void deleteBook(long id) {
        Book book = bookMapper.selectByPrimaryKey(id);
        if (book == null)
            throw new BizException(ResponseCode.UPDATE_CHECK_NULL);

        bookMapper.deleteByPrimaryKey(id);
    }
}
